﻿using Autofac;
using Autofac.Configuration;
using Autofac.Configuration.Elements;
using Kongt.IServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kongt.ServiceProvider
{
    public class Instance<T> where T : IService
    {
        public static T Create 
        {
            get
            {
                ContainerBuilder builder = new ContainerBuilder();
                ConfigurationSettingsReader reader = new ConfigurationSettingsReader("autofac");
                ComponentElement element = reader.SectionHandler.Components.FirstOrDefault<ComponentElement>(item => item.Service.Contains(typeof(T).FullName));
                try
                {
                    if (element == null)
                    {
                        string str2 = typeof(T).Name.Substring(1);
                        string typeName = string.Format("Kongt.Service.{0}, Kongt.Service", str2);
                        Type type = Type.GetType(typeName);
                        if (type == null)
                        {
                            throw new NotImplementedException("未找到" + typeName);
                        }
                        RegistrationExtensions.RegisterType(builder, type).As<T>();
                    }
                    else
                    {
                        RegistrationExtensions.RegisterType<T>(builder);
                        ModuleRegistrationExtensions.RegisterModule(builder, reader);
                    }
                    return ResolutionExtensions.Resolve<T>(builder.Build(0));
                }
                catch (Exception exception)
                {
                    throw new ServiceInstacnceCreateException(typeof(T).Name + "服务实例创建失败", exception);
                }

            }
        }
    }
}




